<?php

$__sys_not_logged_request = true;

require_once dirname(dirname(dirname(__FILE__))).DIRECTORY_SEPARATOR.'inite.php';

$ffff = microtime(true);
define('THIS_DIR', dirname(realpath(__FILE__)));
define('USE_ENCODING', 1);
define('CONTENT_TYPE', 'text/css');
$extension = '.css';
$cache_path = Application::CSSCachePath();

$accept_encodings = Request::o()->acceptEncodings();
$allow_encodings = array_intersect(Application::outputEncodings(), $accept_encodings);

function generateFile($file_name, $file_id, $extension)
{
    $file = translateCSS(file_get_contents(THIS_DIR.DS.$file_name.$extension));

    $css_fname = Application::CSSCachePath().DS.$file_name.'.'.$file_id;
    file_put_contents($css_fname.$extension, $file);

    if (Application::useEncodingForStatic()) {
        foreach (Application::outputEncodings() as $encoding) {
            file_put_contents($css_fname.'.'.$encoding.$extension, encode_string($file, $encoding));
        }
    }
}

function storeInFile($text)
{
    $tmpfname = tempnam(null, '');
    file_put_contents($tmpfname, $text);

    return $tmpfname;
}

function executePHPScript($text)
{
    $result = '';

    $tmpfname = storeInFile($text);
    ob_start();
    include $tmpfname;
    $result = ob_get_clean();
    unlink($tmpfname);

    return $result;
}

function translateCSS($text)
{
    return executePHPScript(
        '<?php'.EOL.
        '$root_url = "'.Application::rootUrlPath().'";'.EOL.
        '$root = "'.Application::rootUrlPath().'";'.EOL.
        '?>'.EOL.
        $text
    );
}

function getFileId($file_name, &$stored_encodings, &$is_stored_nonencoding)
{
    $is_stored_nonencoding = false;
    $stored_encodings = array();
    global $cache_path, $extension;
    $files = scandir($cache_path . DS);
    $id = '';
    $escaped_ext = preg_replace('/([.\[\]*{}()+?])/s', "\\\\\\1", $extension);
    foreach ($files as $file) {
        if (preg_match('/^'.$file_name.'\.([^.]+)(?:\.([^.]+))?'.$escaped_ext.'$/', $file, $matches) && isset($matches[1])) {
            $id = $matches[1];
            if (empty($matches[2])) {
                $is_stored_nonencoding |= true;
            } else {
                $stored_encodings[] = $matches[2];
            }
        }
    }
    return $id;
}

function encode_string($string, $method)
{
    switch ($method) {
    case 'x-gzip':
    case 'gzip':
        return gzencode($string, 9, FORCE_GZIP);

    case 'deflate':
        return  gzdeflate($string, 9);

    default:
        throw new Exception();
    }
}

$file_name = isset($_GET['file']) ? $_GET['file'] : '';
if (strpos($file_name, $extension)===($__g = strlen($file_name) - strlen($extension))) {
    $file_name = substr($file_name, 0, $__g);
}

$file_path = THIS_DIR . DS . $file_name . $extension;
if (! strlen($file_name) || ! file_exists($file_path)) {
    header('HTTP/1.1 404 Not Found');
    exit();
}

$file_id = md5(filemtime($file_path) . filesize($file_path) . Application::rootUrlPath());

$stored_encodings = array();
$is_stored_nonencoding = false;
if ($curr_id = getFileId($file_name, $stored_encodings, $is_stored_nonencoding)) {
    if (($curr_id != $file_id) || ! $is_stored_nonencoding || count(array_diff($stored_encodings, Application::outputEncodings()))) {
        $files = scandir($cache_path.DS);
        $escaped_ext = preg_replace('/([.\[\]*{}()+?])/s', "\\\\\\1", $extension);
        foreach ($files as $file) {
            if (preg_match('/^'.$file_name.'\..*'.$escaped_ext.'$/', $file, $matches)) {
                unlink($cache_path.DS . $matches[0]);
            }
        }
        generateFile($file_name, $file_id, $extension);
    }
} else {
    generateFile($file_name, $file_id, $extension);
}

header('Content-Type: '.CONTENT_TYPE.'; charset='.Application::encoding());

$file_source = $cache_path.DS . $file_name . '.' . $file_id . $extension;
$_was_encoded = '';

if (USE_ENCODING && count($accept_encodings)) {
    $content_length = filesize($cache_path.DS . $file_name . '.' . $file_id . $extension);
    $best_encoding = '';
    $best_compress = 1000.0;
    foreach ($allow_encodings as $encoding) {
        $compress = filesize($cache_path.DS . $file_name . '.' . $file_id . '.'.$encoding.$extension) / $content_length;
        if ($best_compress > $compress) {
            $best_compress = $compress;
            $best_encoding = $encoding;
        }
    }
    if ($best_encoding && $best_compress < 1) {
        $_was_encoded = $best_encoding;
        header('Content-Encoding: ' . $best_encoding);
        header('X-Content-Compressed: '.sprintf('%.1f%%', $best_compress*100));
        $file_source = ($cache_path.DS . $file_name . '.' . $file_id . '.'.$best_encoding.$extension);
    } else {
        $file_source = ($cache_path.DS . $file_name . '.' . $file_id . $extension);
    }
}

function drawMiliSecondValue($value)
{
    return sprintf('%.3f', $value*1000);
}

header('X-Render-Time: '.drawMiliSecondValue(($frr = microtime(true)) - Request::o()->time()).' ms');
header('X-Actual-Time: '.drawMiliSecondValue($frr - $ffff).' ms');
if (!isset($_GET['_store'])) {
    header("Cache-Control: no-store, no-cache, must-revalidate");
    header("Expires: " . date("r"));
} else {
    header("Cache-Control: public");
    header("Expires: " . date("r", strtotime('+1 month')));
    if (!empty($_was_encoded)) {
        header("Vary: \"Content-Encoding\"");
    }
}
//echo date('H:i:s'), "\n";


readfile($file_source);

?>